<?php
namespace app\admin\controller;
//订单控制器
use app\admin\controller\Home;
use app\admin\controller\Cart;
use app\admin\model\Orders;
use app\admin\controller\Group;
use app\admin\model\System;
use app\admin\controller\Coupon;
class Order extends Home
{
	public function __construct(){
		parent::__construct();
	}
	/**
	 * 获取订单列表 zy
	 */
	public function getOrderByStatus(){
		$status = (int)input('status');
		$userId = $this->user['uid'];
		$orderNo = input("orderNo");
		$orderStatus = (int)input("orderStatus",0);
		$goodsName = input("goodsName");
		$shopName = input("shopName");
		$userName = input("userName");
		$pcurr = (int)input("pcurr",0);
		switch($status){
			case 1://待付款
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus =-2 AND o.isPay = 0 AND o.payType = 1 AND o.shopId=sp.shopId ";break;
			case 2://待发货
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus in ( 0,1,2 ) AND o.shopId=sp.shopId ";break;
			case 3://待确认收货
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus =3 AND o.shopId=sp.shopId ";break;
			case 4://待评价
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus = 4 AND o.shopId=sp.shopId ";break;
			case 5://已取消
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus in (-1,-6,-7) AND o.shopId=sp.shopId ";break;
			case 6://拒收、退款
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND (o.orderStatus in (-3,-4,-5) or (o.orderStatus in (-1,-4,-6,-7) and payType =1 AND o.isPay =1)) AND o.shopId=sp.shopId
		";break;
				case 7://待拼团
				    $where = " WHERE o.orderFlag=1 and o.userId = $userId AND o.orderStatus =-10 AND o.shopId=sp.shopId ";break;

			case 8://拒收、退款
				$where = " WHERE o.orderFlag=1 and o.userId = $userId AND (o.orderStatus in (-3,-4,-5) or (o.orderStatus in (-4,-7) and payType =1 AND o.isPay =1)) AND o.shopId=sp.shopId
		";break;
			case 999://全部
				$where = " WHERE o.orderFlag=1 and o.userId = $userId  AND o.shopId=sp.shopId
		";break;
		}
		$sql = "SELECT o.istuan,o.orderId,o.orderNo,o.shopId,o.kuaidi,o.orderunique,o.orderStatus,o.userName,o.totalMoney,o.realTotalMoney,o.deliverMoney,
		o.createTime,o.payType,o.isRefund,o.isAppraises,sp.shopName
		FROM wst_orders o,wst_shops sp".$where;
		if($orderNo!=""){
			$sql .= " AND o.orderNo like '%$orderNo%'";
		}
		if($userName!=""){
			$sql .= " AND o.userName like '%$userName%'";
		}
		if($shopName!=""){
			$sql .= " AND sp.shopName like '%$shopName%'";
		}
		$sql .= " order by o.orderId desc";
		//echo $sql;die;
		$pages = db('Orders')->query($sql);
		$orderList = $pages;
		if(count($orderList)>0){
			$orderIds = array();
			for($i=0;$i<count($orderList);$i++){
				$order = $orderList[$i];
				$orderIds[] = $order["orderId"];
			}
			//获取涉及的商品
			$sql = "SELECT og.goodsId,og.goodsName,og.goodsAttrName,og.goodsThums,og.orderId,og.goodsPrice,og.goodsNums FROM wst_order_goods og
					WHERE og.orderId in (".implode(',',$orderIds).")";
			$glist = db('Order_goods')->query($sql);
			/*$goodslist = array();
			for($i=0;$i<count($glist);$i++){
				$goods = $glist[$i];
				$goodslist[$goods["orderId"]][] = $goods;
			}*/
			$goodslist = array();
			for($i=0;$i<count($glist);$i++){
				$wocao = db('Goods_appraises')->where(array('goodsId'=>$glist[$i]['goodsId'],'orderId'=>$glist[$i]['orderId']))->find();
                                $goods_type =  db('Goods')->where(array('goodsId'=>$glist[$i]['goodsId']))->find();
				
                                $glist[$i]['goods_type'] = $goods_type['goods_type'];
                                if($wocao){
					$goods = $glist[$i]['pingjia'] = 1;
				}else{
					$goods = $glist[$i]['pingjia'] = 0;
				}
				//dump($glist[$i]);
				$goods = $glist[$i];
				$goodslist[$goods["orderId"]][] = $goods;
			}
			//放回分页数据里
		for($i=0;$i<count($orderList);$i++){
				$order1 = $orderList[$i];
				$order1["goodslist"] = $goodslist[$order1['orderId']];
				$return_order[$i] = $order1;
			}
			return jsonp($return_order);
		}else{
			return jsonp($orderList);
		}
	}
	/**
	 * 新增会员收货地址 type 1 新增 2 修改 3 修改默认地址  LB
	 */
	public function addUserAddress(){
		$type = (int)input('type');
		$id   = (int)input('id');
		$data = array();
		$data["userId"]    = $this->user['uid'];
		$data["userName"]  = input("userName");
		$i["areaName1"]   = input("areaId1");
		$i["areaName2"]   = input("areaId2");
		$i["areaName3"]   = input("areaId3");
		$i1 = db('Areas')->where(['areaName'=>$i["areaName1"]])->find()['areaId'];
		$i2 = db('Areas')->where(['areaName'=>$i["areaName2"]])->find()['areaId'];
		$i3 = db('Areas')->where(['areaName'=>$i["areaName3"]])->find()['areaId'];
        $data['areaId1'] = (int)$i1;
        $data['areaId2'] = (int)$i2;
	    if(!is_null($i3)){
        	$data['areaId3'] = $i3;
        }
        $communityId = (int)input("communityId");
        if(!is_null($communityId)){
            $data["communityId"] = $communityId;
        }
		if(input("userPhone")!=''){
			$data["userPhone"] = input("userPhone");
		}else{
			$data["userTel"]   = input("userTel");
		}
		$data["address"] = input("address");
		$data["isDefault"] = (int)input("isDefault",0);
		$data["addressFlag"] = 1;
		$data["createTime"] = date('Y-m-d H:i:s');
		//dump($data);
		if($type == 1){
			if($this->checkEmpty($data,true)){
				if($data["isDefault"] == 1){
		        db("User_address")->where(['userId'=>$data["userId"]])->update(['isDefault'=>0]);
		    }
				$rs = db('user_address')->insertGetId($data);
				$id = $rs;
			}else{
			    $back = ['status'=>-3,'msg'=>'参数不全'];
			    return jsonp($back);
			}
		}elseif($type == 2){
		    if($data["isDefault"] == 1){
		        db("User_address")->where(['userId'=>$data["userId"]])->update(['isDefault'=>0]);
		    }
		    $rs = db('user_address')->where('addressId='.$id)->update($data);
		}
		if(!$rs){
			$back = ['status'=>-2,'msg'=>'修改失败，请稍后再试'];
			return jsonp($back);
		}
		
		$back = ['status'=>1,'msg'=>'成功'];
		return jsonp($back);
	}
	//删除地址
  	public function delAddress(){
	    $aid = (int)input("addressId");
	    $dela = db('user_address')->where('addressId='.$aid)->delete();
	    if($dela){
	        $back = ['status'=>1,'msg'=>'收货地址删除成功'];
	        return jsonp($back);
	    }
	}
	//修改地址
	public function defAddress(){
	      $id = (int)input('addressId');
	      if($id){
	          $data_default['isDefault'] = 0;
	          db('user_address')->where('userId='.$this->user['uid'])->update($data_default);
	          $data['isDefault'] = 1;
	          $def = db('user_address')->where('addressId='.$id)->update($data);
	          if($def){
	               $back = ['status'=>1,'msg'=>'成功'];
	               return jsonp($back);
	            }else{
	          $back = ['status'=>-1,'msg'=>'失败'];
	          return jsonp($back);
	           }
	      }else{
	          $back = ['status'=>-1,'msg'=>'失败'];
	          return jsonp($back);
	      }
	  }
	/**
	 * 订单结算页面 zy
	 */
	public function jiesuan(){
	    $cart = new Cart();
	    $a = $cart->moniCart();
	    if($a['status'] != 1){
	        return jsonp($a);
	    }
	    $is_tuan = input('istuan');
		if($is_tuan == 3){
			$API_GROUP = new Group();
			$group_id = input('group_id');
			$group = $API_GROUP->getGroup($group_id);
			if(!$group){
				$back=array('status'=>-2,'msg'=>'当前团购已结束');
				return jsonp($back);
			}
			if($group['uid'] ==  $this->user['uid']){
				$back=array('status'=>-101,'msg'=>'不可以参加自己的团购');
				return jsonp($back);
			}
			//获取商品数据
			$good = db('Goods')->where('goodsId='.$group['gid'])->find();
			//获取所有加入团购的人
			$member_order = db('Orders')->where('group_id='.$group['id'])->select();
			foreach($member_order as $k=>$v){
				$where_user['userId'] = $v['userId'];
				$member[$k]['username'] =  db('Users')->where($where_user)->find()['loginName'];
			}
			$group_info['group'] 		= $group;
			$group_info['good'] 		= $good;
			$group_info['member'] 	= $member;
			$group_info['now_time']  = time();
			$group_info['end_time']  = $group['add_time']+24*3600;
			$data['group_info'] = $group_info;//团购信息
		}
		//获取购买的商品订单 购物车
		$rdata = $this->getPayCart($is_tuan);
		if($rdata["cartnull"]==1){
			$back=array('status'=>-1,'msg'=>'获取订单失败');
			return jsonp($back);
		}
		//$rdata[''] = ;
		$catgoods     = $rdata["cartgoods"];
		$shopColleges = $rdata["shopColleges"];
		$startTime    = $rdata["startTime"];
		$endTime      = $rdata["endTime"];
		$gtotalMoney  = $rdata["gtotalMoney"];//商品总价（去除配送费）
		$totalMoney   = $rdata["totalMoney"];//商品总价（含配送费）
		$totalCnt     = $rdata["totalCnt"];
		$userId       = $this->user['uid'];
		//获取本人的邮寄地址列表 
		$userAddressList = $this->queryByUserAndCity($userId);
		foreach ($userAddressList as $k=>&$v){
			$v['areaId1'] = db('Areas')->where(['areaId'=>$v['areaId1']])->find()['areaName'];
			$v['areaId2'] = db('Areas')->where(['areaId'=>$v['areaId2']])->find()['areaName'];
			$v['areaId3'] = db('Areas')->where(['areaId'=>$v['areaId3']])->find()['areaName'];
			$v['isDefault'] = $v['isDefault']?true:false;
		}
		$userAddressList_status = $userAddressList?1:0;
		//资金与金钱兑换比例（config表 id 42）
		$baseMoney = 1;
		$user = db('Users')->where(" userId =".$userId)->find();
		$useScore = floor($user["money_shangcheng"]);				//个人的可用余额 商城积分
		$scoreMoney = $baseMoney*floor($user['money_shangcheng']);  //使用额度 商城积分
		if($totalMoney<$scoreMoney){
			//订单金额小于积分金额
			$useScore = floor($totalMoney);
			$scoreMoney = $baseMoney*floor($totalMoney);
		}
		//新增加 代金券
		$daijinMoneyDaijin = 1;
		$goodsDaijin = $rdata["daijin"];
		$DaijinMoney = 0;
		if(!empty($goodsDaijin)&&$goodsDaijin!=0){
			$useDaijin = floor($user["money_daijin"]);		         //可用余额  代金券
			$DaijinMoney = $daijinMoneyDaijin*floor($user['money_daijin']);  //使用额度
			if($goodsDaijin<$DaijinMoney){//订单金额小于积分金额
				$useDaijin = floor($goodsDaijin);
				$DaijinMoney = $daijinMoneyDaijin*floor($goodsDaijin);
			}
		}
		$data['goods']                                  = $rdata;//要购买的商品
		$data['userAddress']['userAddressList']         = $userAddressList;//购买人的地址
		$data['userAddress']['userAddressList_status']  = $userAddressList_status;//购买人的地址状态
		//$data['payments']                               = $payments;//支付方式
		$data['scoreMoney']                             = $scoreMoney;//可用商城积分
		$data['MYscoreMoney']                           = $user["money_shangcheng"];//我的商城积分
		$data['DaijinMoney']                            = $DaijinMoney;//可用代金券
		$data['MYDaijinMoney']                          = $user['money_daijin'];//我的代金券
		$data['money_tuanbei']                          = $user['money_tuanbei'];//我的团呗币
		return jsonp($data);
	}
	/**
	 * 下单
	 */
	public function submitOrder(){
		$userId = $this->user['uid'];
		$user = db('Users')->where(" userId =".$userId)->find();
		if($user['userId']!='6407'){
			$back=array('status'=>-3,'msg'=>'暂为开通');
					return jsonp($back);
		}
		$totalMoney = 0;
		$totalCnt = 0;
		//获取要购买的商品
		$sql = "select * from wst_cart where userId = $userId and isCheck=1 and goodsCnt>0";
		$shopcart = db()->query($sql);
		$catgoods = array();
		$order = array();
			//整理及核对购物车数据
			$cartIds = array();
			for($i=0;$i<count($shopcart);$i++){
				$cgoods = $shopcart[$i];
				$goodsId = (int)$cgoods["goodsId"];
				$goodsAttrId = (int)$cgoods["goodsAttrId"];
				$goods = $this->getGoodsSimpInfo($goodsId,$goodsAttrId);
				//核对商品是否符合购买要求
				if(empty($goods)){
					$back=array('status'=>-2,'msg'=>'找不到指定的商品');
					return jsonp($back);
				}
				if($goods['goodsStock']<=0){
					$back=array('status'=>-3,'msg'=>'对不起，商品库存不足');
					return jsonp($back);
				}
				if($goods['isSale']!=1){
					$back=array('status'=>-4,'msg'=>'对不起，商品库已下架');
					return jsonp($back);
				}
				$goods["collor"] = $shopcart[$i]['collor'];
				$goods["cnt"]    = $cgoods["goodsCnt"];
				$catgoods[$goods["shopId"]]["shopgoods"][] = $goods;
				$catgoods[$goods["shopId"]]["deliveryFreeMoney"] = $goods["deliveryFreeMoney"];//店铺免运费最低金额
				$catgoods[$goods["shopId"]]["deliveryMoney"] = $goods["deliveryMoney"];//店铺免运费最低金额
				$totalMoney += $goods["cnt"]*$goods["marketPrice"];
				$cartIds[] = $cgoods["cartId"];
			}
			foreach($catgoods as $key=> $cshop){
				$cartgoods_zy[$i] = $cshop;
				$i++;
				//单一店铺合计金额
				$shop_total_money = 0;
				$shop_total_cnt   = 0;
				foreach($cshop['shopgoods'] as $k=>$v){
				    $shop_total_money += $v["cnt"]*$v["marketPrice"];
				    $shop_total_cnt   += $v["cnt"];
				}
				$cshop["totalMoney"] = $shop_total_money;
				$cshop["totalCnt"]   = $shop_total_cnt;
				$catgoods[$key]['totalMoney'] = $cshop["totalMoney"];
				//if($cshop["totalMoney"]<$cshop["deliveryFreeMoney"]){
			    $totalMoney = $totalMoney + $cshop["deliveryMoney"];
			    //}
			}
			//准备数据
			$consigneeId = (int)input("consigneeId");//对应user_address  的id
			$payway      = 1;//支付方式  1  余额支付  2  积分支付
			$isself      = (int)input("isself");//自己提取 没有邮费 
			$needreceipt = (int)input("needreceipt");//是否需要发票 1需要 0不需要
			$orderunique = WSTGetMillisecond().$userId;//流水号
			$group_id = input('group_id');
			//添加订单表 相关数据处理 减余额 代金券
			$istuan = 1;
			$ordersInfo = $this->addOrders($userId,$consigneeId,$payway,$needreceipt,$catgoods,$orderunique,$isself,$istuan,$group_id);
			if(isset($ordersInfo['status'])){
			    if($ordersInfo['status'] == -11){
			        $back['addressStatus'] = -11;
			    }
			}else{
			    if(!empty($cartIds)){ 
			        $cartIds_array   = implode(",",$cartIds);
			        $where['userId'] = $userId;
			        $where['cartId'] = array('in',$cartIds_array);
			        db('Cart')->where($where)->delete();
			    }
			}
			//获取订单和里面的钱
			$order = db('Orders')->where('orderId='.$ordersInfo['orderIds'][0])->find();
			$return['money'] = $order['totalMoney'];
			$return['orderunique'] = $orderunique;
			$return['status'] = $istuan;
			$back=array('status'=>1,'msg'=>$return);
			return jsonp($back);
	}
	//开团详情
	public function getGroupInfo(){
	    $orderunique = input('orderunique');
		$API_GROUP = new Group();
		if($orderunique){
			//获取订单和里面的钱
			$order = db('Orders')->where('orderunique='.$orderunique)->find();
			 //获取团购数据
			$group = $API_GROUP->getGroup($order['group_id']);
			$data['order'] 		= $order;
		}else{
			$group_id = input('group_id');
			$group = $API_GROUP->getGroup($group_id);
		}
		if(!$group){
			$back=array('status'=>-2,'msg'=>'该团购已结束');
			return jsonp($back);
		}
	    //获取商品数据
		$good = db('Goods')->where('goodsId='.$group['gid'])->find();
		//重置商品价格
		$goodsId = $group['gid'];
		$sql = "SELECT sc.catName,sc2.catName as pCatName, g.*,shop.shopName,shop.deliveryType,ga.id goodsAttrId,ga.attrPrice,ga.attrTuanPrice,ga.attrStock,
		shop.shopAtive,shop.shopTel,shop.shopImg,shop.shopAddress,shop.deliveryTime,shop.isInvoice, shop.deliveryStartMoney,g.goodsStock,shop.deliveryFreeMoney,shop.qqNo,
		shop.deliveryMoney ,g.goodsSn,shop.serviceStartTime,shop.serviceEndTime FROM wst_goods g left join wst_goods_attributes ga on g.goodsId=ga.goodsId and ga.isRecomm=1, wst_shops shop, wst_shops_cats sc
		LEFT JOIN wst_shops_cats sc2 ON sc.parentId = sc2.catId
		WHERE g.goodsId = $goodsId AND shop.shopId=sc.shopId AND sc.catId=g.shopCatId1 AND g.shopId = shop.shopId AND g.goodsFlag = 1 ";
		$rs = db()->query($sql);
		if(!empty($rs) && $rs[0]['goodsAttrId']>0){
			$good['shopPrice'] = $rs[0]['attrTuanPrice'];
			$good['marketPrice'] = $rs[0]['attrPrice'];
			$good['goodsStock'] = $rs[0]['attrStock'];
		}
		//获取所有加入团购的人
		$member_order = db('Orders')->where('group_id='.$group['id'])->select();
		foreach($member_order as $k=>$v){
			$where_user['userId'] = $v['userId'];
			$member[$k]['username'] =  db('Users')->where($where_user)->find()['loginName'];
		}
	    $data['group'] 		= $group;
	    $data['good'] 		= $good;
	    $data['member'] 	= $member;
	    $data['now_time']  = time();
	    $data['end_time']  = $group['add_time']+24*3600;
	    $back=array('status'=>1,'msg'=>$data);
	    return jsonp($back);
	}
	//本商品团购列表
	public function getGroupList(){
		$gid = input('gid');
	    //获取团购数据
	    $API_GROUP = new Group();
	    $group = $API_GROUP->getGroupList($gid);
		foreach($group as $k=>$v){
			$where_user['userId'] = $v['uid'];
			$group[$k]['username'] = db('Users')->where($where_user)->find()['loginName'];
			$group[$k]['now_time'] = time();
			$group[$k]['end_time'] = $v['add_time']+24*3600;
		}
	    $back=array('status'=>1,'msg'=>$group);
	    return jsonp($back);
	}
	
	/**
	 * 获取要购买的商品（选中）
	 * @return number|Ambigous <number, unknown>
	 */
	 public function getPayCart($tuan){
	     
		$userId = $this->user['uid'];
		//获取购物车中被选中的商品
		$sql = "select * from wst_cart where userId = ".$userId." and isCheck=1 and goodsCnt>0";
		$shopcart = db()->query($sql);
		$rdata["cartnull"] = 0;
		if(empty($shopcart)){
			$rdata["cartnull"] = 1;
			return $rdata;
		}
		$cartgoods = array();
		$shopColleges = array();
		$paygoods = array();
		
		$startTime = 0;
		$endTime = 24;
	
		$gtotalMoney = 0;//商品总价（去除配送费）
		$totalMoney  = 0;//商品总价（含配送费）
		$totalCnt    = 0;
		$daijin      = 0;
		for($i=0;$i<count($shopcart);$i++){
			$cgoods = $shopcart[$i];
			$obj["goodsId"] = (int)$cgoods["goodsId"];
			$obj["goodsAttrId"] = (int)$cgoods["goodsAttrId"];
				
			$paygoods[] = $obj["goodsId"];
			$goods = $this->getGoodsForCheck($obj);
			$goods['collor'] = $shopcart[$i]['collor'];
			$goods["ischk"] = $cgoods["isCheck"];
			$goods["cnt"] = $cgoods["goodsCnt"];
			$totalCnt += $cgoods["goodsCnt"];
			if($tuan != 0){
			    $totalMoney += $goods["cnt"]*$goods["shopPrice"];
			    $gtotalMoney += $goods["cnt"]*$goods["shopPrice"];
			}else{
			    $totalMoney += $goods["cnt"]*$goods["marketPrice"];
			    $gtotalMoney += $goods["cnt"]*$goods["marketPrice"];
			}
			$ommunitysId = $this->getShopCommunitysId($goods["shopId"]);
			$shopColleges[$goods["shopId"]] = $ommunitysId;
			if($startTime<$goods["startTime"]){
				$startTime = $goods["startTime"];
			}
			if($endTime>$goods["endTime"]){
				$endTime = $goods["endTime"];
			}
			$daijin += $goods["daijin"]*$goods["cnt"];
			$cartgoods[$goods["shopId"]]["shopname"]             = $goods['shopName'];
			$cartgoods[$goods["shopId"]]["shopid"]               = $goods['shopId'];
			$cartgoods[$goods["shopId"]]["shopgoods"][]          = $goods;
			$cartgoods[$goods["shopId"]]["deliveryFreeMoney"]    = $goods["deliveryFreeMoney"];//店铺免运费最低金额
			$cartgoods[$goods["shopId"]]["deliveryMoney"]        = $goods["deliveryMoney"];//店铺配送费
			$cartgoods[$goods["shopId"]]["deliveryStartMoney"]   = $goods["deliveryStartMoney"];//店铺配送费
		}
		$i=0;
		foreach($cartgoods as $key=> $cshop){
		
			$cartgoods_zy[$i] = $cshop;	
			$i++;
			//单一店铺合计金额
			$shop_total_money = 0;
			$shop_total_cnt   = 0;
			
			if($tuan == 1){
			    foreach($cshop['shopgoods'] as $k=>$v){
			        $shop_total_money += $v["cnt"]*$v["shopPrice"];
			        $shop_total_cnt   += $v["cnt"];
			    }
			}else{
			    foreach($cshop['shopgoods'] as $k=>$v){
			        $shop_total_money += $v["cnt"]*$v["marketPrice"];
			        $shop_total_cnt   += $v["cnt"];
			    }
			}
			
			
			$cshop["totalMoney"] = $shop_total_money;
			$cshop["totalCnt"]   = $shop_total_cnt;
			//if($cshop["totalMoney"]<$cshop["deliveryFreeMoney"]){
				$totalMoney = $totalMoney + $cshop["deliveryMoney"];
			//}
		}
		session('ORDER_GOODS',$paygoods);
		$rdata["totalMoney"]   = $totalMoney;//总价（包含邮费）
		$rdata["daijin"]       = $daijin;//代金券
		$rdata["totalCnt"]     = $totalCnt;//商品总数
		$rdata["gtotalMoney"]  = $gtotalMoney;//商品总价（不包括邮费）
		$rdata["cartgoods"]    = $cartgoods_zy;//商品详情
		$rdata["shopColleges"] = $shopColleges;//店铺配送信息
		$rdata["startTime"]    = $startTime;//商品开始时间？？
		$rdata["endTime"]      = $endTime;//同上？？
		$rdata["goods_type"]   = db('Goods')->field('goods_type,goodsId')->where(['goodsId'=>$obj['goodsId']])->find()['goods_type'];
		return $rdata;
	}
	/**
	 * 获取商品信息-购物车/核对订单用
	 */
	private function getGoodsForCheck($obj){
		$goodsId = (int)$obj["goodsId"];
		$goodsAttrId = (int)$obj["goodsAttrId"];
		$sql = "SELECT sc.catName,sc2.catName as pCatName, g.attrCatId,g.daijin,g.goodsThums,g.goodsId,g.goodsName,g.shopPrice,g.goodsStock,g.shopId,shop.shopName,shop.qqNo,shop.deliveryType,shop.shopAtive,shop.shopTel,shop.shopAddress,shop.deliveryTime,shop.isInvoice,shop.deliveryStartMoney,g.goodsStock,shop.deliveryFreeMoney,shop.deliveryMoney ,g.goodsSn,shop.serviceStartTime startTime,shop.serviceEndTime endTime
		FROM wst_goods g, wst_shops shop, wst_shops_cats sc
		LEFT JOIN wst_shops_cats sc2 ON sc.parentId = sc2.catId
		WHERE g.goodsId = $goodsId AND shop.shopId=sc.shopId AND sc.catId=g.shopCatId1 AND g.shopId = shop.shopId AND g.goodsFlag = 1 ";
		$rs = db()->query($sql)[0];
		if(!empty($rs) && $rs['attrCatId']>0){
			$sql = "select ga.id,ga.attrPrice,ga.attrTuanPrice,ga.attrStock,a.attrName,ga.attrVal,ga.attrId 
					from wst_attributes a,wst_goods_attributes ga
			        where a.attrId=ga.attrId and a.catId=".$rs['attrCatId']." and ga.goodsId=".$rs['goodsId']." and id=".$goodsAttrId;
			$priceAttrs = db()->query($sql)[0];
			if(!empty($priceAttrs)){
				$rs['attrId'] = $priceAttrs['attrId'];
				$rs['goodsAttrId'] = $priceAttrs['id'];
				$rs['attrName'] = $priceAttrs['attrName'];
				$rs['attrVal'] = $priceAttrs['attrVal'];
				$rs['shopPrice'] = $priceAttrs['attrTuanPrice'];
				$rs['marketPrice'] = $priceAttrs['attrPrice'];
				$rs['goodsStock'] = $priceAttrs['attrStock'];
			}
		}
		$rs['goodsAttrId'] = (int)$rs['goodsAttrId'];
		return $rs;
	}
	/**
	 * 获取店铺配送区
	 *
	 * @param unknown_type $shopId
	 */
	private function getShopCommunitysId($shopId){
		$sql = "SELECT communityId FROM wst_shops_communitys WHERE shopId = $shopId ";
		$communitys = db()->query($sql);
		$communitysId = array();
		for($i=0;$i<count($communitys);$i++){
			$communitysId[] = $communitys[$i]["communityId"];
		}
		return implode(",",$communitysId) ;
	}
	/**
	 * 根据用户以及所在城市获取列表
	 */
	private function queryByUserAndCity($userId){
		$sql = "select * from wst_user_address where isDefault = 1 and userId = ".$userId." ORDER BY isDefault desc";
		return db()->query($sql);
	}
	/**
	 * 定位所在城市
	 */
	private function getDefaultCity(){
		$areaId2 = (int)input('city',0);
		if($areaId2==0){
			$areaId2 = (int)session('areaId2');
		}
		//检验城市有效性
		if($areaId2>0){
			$sql ="SELECT areaId FROM wst_areas WHERE isShow=1 AND areaFlag = 1 AND areaType=1 AND areaId=".$areaId2;
			$rs = $this->query($sql);
			if($rs[0]['areaId']=='')$areaId2 = 0;
		}else{
			$areaId2 = (int)$_COOKIE['areaId2'];
		}
		//定位城市
		if($areaId2==0){
			//IP定位
			$iparea = getIPAddress();
			if(!empty($iparea)){
				$where = array();
				$where['areaName'] = array('like', '%'.$iparea['city'].'%');
				$where['isShow'] = 1;
				$where['areaFlag'] = 1;
				$where['areaType'] = 1;
				$rs = $this->where($where)->getField('areaId');
				if(intval($rs)>0){
					$areaId2 = intval($rs);
				}else{
					$areaId2 = $GLOBALS['CONFIG']['defaultCity'];
				}
			}else{
				$areaId2 = $GLOBALS['CONFIG']['defaultCity'];
			}
		}
		session('areaId2',$areaId2);
		setcookie("areaId2", $areaId2, time()+3600*24*90);
		return $areaId2;
		 
	}
	/**
	 * 获取支付列表
	 */
	private function getPayList(){
		return;
		$payments = db('Payments')->where('enabled=1')->order('payOrder asc')->select();
		$paylist = array();
		foreach ($payments as $key => $payment) {
			$payConfig = json_decode($payment["payConfig"]) ;
			foreach ($payConfig as $key2 => $value) {
				$payment[$key2] = $value;
			}
			//$payments[$key] = $payment;
			if($payment["isOnline"]){
				$paylist["onlines"][] = $payment;
			}else{
				$paylist["unlines"][] = $payment;
			}
		}
		return $paylist;
	}
	/**
	 * 获取城市下的区
	 */
	public function getDistricts($parentId){
		return db('Areas')->where('areaFlag=1 and isShow=1 and parentId='.$parentId)->field('areaId,areaName')->order('parentId, areaSort')->select();
	}

    public function aaaaaa(){
        //$qd = $this->checkLogin();
        $token = input('token')?input('token'):1;
        $uid = db('Token')->where(['token'=>$token])->find();
        
		
		$payments = $this->getList();
		$this->assign("payments",$payments["onlines"]);

		$obj["orderId"] = input("orderId")?input("orderId"):1;
		$data = $this -> getPayOrders($obj);
		$orders = $data["orders"];
		$needPay = $data["needPay"];
		$list["orderId"]=$obj["orderId"];
		$list["orders"]=orders;
		$list["needPay"]=$needPay;
		$list["orderCnt"]=count($orders);
		
		dump($list);
	}
	/**
	 * 用户确认收货订单
	 */
	public function orderConfirm(){
		$USER = $this->user;
		$morders = new Orders();
		$obj["userId"] = (int)$USER['uid'];
		$obj["orderId"] = (int)input("orderId");
		$obj["type"] = (int)input("type")?(int)input("type"):1;
		$rs = $morders->orderConfirm($obj);
		return jsonp($rs);
	}
	/**
	 * 生成订单
	 */
	private function addOrders($userId,$consigneeId,$payway,$needreceipt,$catgoods,$orderunique,$isself,$istuan,$group_id){
		$orderInfos = array();
		$orderIds = array();
		$orderNos = array();
		$remarks     = input("remarks");
		$isDaijinPay = input('isDaijinPay');
		//前台传来的 一共用了多少代金券
		$daijinMoneyUsed = input("daijinquanUsed");
		//获取详细地址信息
		$addressInfo = $this->getAddressDetails($consigneeId);
		if(!$addressInfo){
		    $back = ['status'=>-11,'msg'=>'收货地址为空'];
		    return $back;
		}
		//对每一件商品循环处理
		foreach ($catgoods as $key=> $shopgoods){
			//生成订单ID
			$orderSrcNo = db('orderids')->insertGetId(array('rnd'=>microtime(true)));
			$orderNo = $orderSrcNo."".(fmod($orderSrcNo,7));
			//创建订单信息
			$data = array();
			$pshopgoods = $shopgoods["shopgoods"];
			$shopId = $pshopgoods[0]["shopId"];
			$data["orderNo"]    = $orderNo;
			$data["shopId"]     = $shopId;
			$data["userId"]     = $userId;
			$data["orderFlag"]  = 1;
			$data["totalMoney"] = $shopgoods["totalMoney"];
			if($isself==1){//自提
				$deliverMoney = 0;
			}else{
				$deliverMoney = $shopgoods["deliveryMoney"];
			}
			$deliverType = intval($pshopgoods[0]["deliveryType"]);
			$data["deliverMoney"] = $deliverMoney;
			$data["payType"]       = $payway;
			$data["deliverType"]   = $deliverType;
			$data["userName"]      = $addressInfo["userName"];
			$data["areaId1"]       = $addressInfo["areaId1"];
			$data["areaId2"]       = $addressInfo["areaId2"];
			$data["areaId3"]       = $addressInfo["areaId3"];
			$data["communityId"]   = $addressInfo["communityId"];
			$data["userAddress"]   = $addressInfo["paddress"]." ".$addressInfo["address"];
			$data["userTel"]       = $addressInfo["userTel"];
			$data["userPhone"]     = $addressInfo["userPhone"];
			$data['orderScore']    = floor($data["totalMoney"]);
			$data["isInvoice"]     = $needreceipt;
			$data["orderRemarks"]  = $remarks;
			$data["requireTime"]   = input("requireTime");
			$data["invoiceClient"] = input("invoiceClient");
			$data["isAppraises"]   = 0;
			$data["isSelf"]        = $isself;
			$data["isTuan"]        = $istuan;
			$data["group_id"]      = $group_id;
			$isScorePay = (int)input("isScorePay",0);
			$scoreMoney = 0;
			$useScore = 0;
			if($GLOBALS['CONFIG']['poundageRate']>0){
				$data["poundageRate"] = (float)$GLOBALS['CONFIG']['poundageRate'];
				$data["poundageMoney"] = $data["totalMoney"] * $data["poundageRate"] / 100;
			}else{
				$data["poundageRate"] = 0;
				$data["poundageMoney"] = 0;
			}
			//资金与金钱兑换比例（config表 id 42）
			$baseMoney = 1;
			//余额支付 积分支付 
			if( $isScorePay==1){
				$sql = "select userId,userScore,money_shangcheng from wst_users where userId=$userId";
				$user = db()->query($sql)[0];
				$useScore = floor($user["money_shangcheng"]);
				$scoreMoney = $baseMoney*$useScore;
				$orderTotalMoney = $shopgoods["totalMoney"]+$deliverMoney;
				if($orderTotalMoney<$scoreMoney){//订单金额小于积分金额
					$useScore = floor($orderTotalMoney/$baseMoney);
					$scoreMoney = $baseMoney*floor($orderTotalMoney/$baseMoney);
				}
				$data["useScore"] = $useScore;
				$data["scoreMoney"] = $scoreMoney;
			}
			$needPay = $shopgoods["totalMoney"]+$deliverMoney - $scoreMoney;
			$data["realTotalMoney"] =  $needPay?$needPay:0.01;
			$data["needPay"] = $needPay?$needPay:0.01;
			$DaijinMoney  = 0;
			//代金券支付
			//TODO
			$DaijinMoney_true = 0;
			if( $isDaijinPay==1){
				$baseMoney = 1;//1
				$sql = "select userId,userScore,money_daijin from wst_users where userId=$userId";
				$user = db()->query($sql)[0];
				//个人的代金券
				$useDaijin= floor($user["money_daijin"]);
				//对应本商品可用的代金券\
				foreach ($shopgoods['shopgoods'] as $k_goods=>$v_goods){
					$good_obj["goodsId"] = (int)$v_goods["goodsId"] ;
					$good_obj["goodsAttrId"] = (int)$v_goods["goodsAttrId"];
					$DaijinMoney += $this->getGoodsForCheck($good_obj)['daijin']*$v_goods['cnt'];
				}
				if($daijinMoneyUsed>$DaijinMoney){
					//本商品用的代金券
					$DaijinMoney_true = $DaijinMoney;
				}else{
					$DaijinMoney_true = $daijinMoneyUsed;
				}
				//一共的代金券减去用过的  即剩下商品可用的数额
				$daijinMoneyUsed = $daijinMoneyUsed-$DaijinMoney_true;
				$data["userDaijin"] = $useDaijin;
				$data["daijinMoney"] = $DaijinMoney_true;
			}
			$needPay = $data["needPay"] - $DaijinMoney_true;
			if($needPay < 0){
				$needPay = 0.01;
			}
			$data["realTotalMoney"] =  $needPay?$needPay:0.01;
			$data["needPay"] = $needPay?$needPay:0.01;
				
			$data["createTime"] = date("Y-m-d H:i:s");
			if($payway==1){
				$data["orderStatus"] = -2;
			}else{
				$data["orderStatus"] = 0;
			}
			$data["orderunique"] = $orderunique;
			$data["isPay"] = 0;
			if($data["needPay"]==0){
				$data["isPay"] = 1;
			}
			$orderId = db('Orders')->insertGetId($data);
			//订单创建成功则建立相关记录
			if($orderId>0){
				if($GLOBALS['CONFIG']['isOpenScorePay']==1 && $isScorePay==1 && $useScore>0){//积分支付
					$rs = db('Users')->where('userId='.$userId)->setDec('money_shangcheng',$useScore);
					$data = array();
					$data["userId"] = $userId;
					$data["money"] = $useScore;
					$data["finance_type"] = 3;
					$data["content"] = "订单支付-商城余额";
					$data["type"] = 2;
					$data["add_time"] = date('Y-m-d H:i:s');
					db('Finance')->insert($data);
				}
				if($isDaijinPay==1 && $useDaijin>0){//代金券支付
					$rs = db('Users')->where('userId='.$userId)->setDec('money_daijin',$DaijinMoney_true);
					$data = array();
					$data["userId"] = $userId;
					$data["money"] = $DaijinMoney;
					$data["finance_type"] = 3;
					$data["content"] = "订单支付-代金券";
					$data["type"] = 2;
					$data["add_time"] = date('Y-m-d H:i:s');
					db('Finance')->insert($data);
				}
				$orderIds[] = $orderId;
				//建立订单商品记录表
				foreach ($pshopgoods as $key=> $sgoods){
					$data = array();
					$data["orderId"] = $orderId;
					$data["goodsId"] = $sgoods["goodsId"];
					$data["goodsAttrId"] = (int)$sgoods["goodsAttrId"];
					if($sgoods["attrVal"]!='')$data["goodsAttrName"] = $sgoods["attrName"].":".$sgoods["attrVal"].' 颜色:'.$sgoods['collor'];
					$data["goodsNums"] = $sgoods["cnt"];
					if($istuan == 1){
					    $data["goodsPrice"] = $sgoods["shopPrice"];
					}else{
					    $data["goodsPrice"] = $sgoods["marketPrice"];
					}
					
					$data["goodsName"] = $sgoods["goodsName"];
					$data["goodsThums"] = $sgoods["goodsThums"];
					db('order_goods')->insert($data);
				}
				if($payway==0){
					//建立订单记录
					$data = array();
					$data["orderId"] = $orderId;
					//TODO
					//$data["logContent"] = ($pshopgoods[0]["deliverType"]==0)? "下单成功":"下单成功等待审核";
					$data["logContent"] = "下单成功";
					$data["logUserId"] = $userId;
					$data["logType"] = 0;
					$data["logTime"] = date('Y-m-d H:i:s');
					db('log_orders')->insert($data);
					//建立订单提醒
					$sql ="SELECT userId,shopId,shopName FROM wst_shops WHERE shopId=$shopId AND shopFlag=1  ";
					$users = db()->query($sql);
					for($i=0;$i<count($users);$i++){
						$data = array();
						$data["orderId"] = $orderId;
						$data["shopId"] = $shopId;
						$data["userId"] = $users[$i]["userId"];
						$data["userType"] = 0;
						$data["remindType"] = 0;
						$data["createTime"] = date("Y-m-d H:i:s");
						db('order_reminds')->insert($data);
					}
					//修改库存
					foreach ($pshopgoods as $key=> $sgoods){
						$sql="update wst_goods set goodsStock=goodsStock-".$sgoods['cnt']." where goodsId=".$sgoods["goodsId"];
						db()->query($sql);
						if((int)$sgoods["goodsAttrId"]>0){
							$sql="update wst_goods_attributes set attrStock=attrStock-".$sgoods['cnt']." where id=".$sgoods["goodsAttrId"];
							db()->query($sql);
						}
					}
				}else{
					$data = array();
					$data["orderId"] = $orderId;
					$data["logContent"] = "订单已提交，等待支付";
					$data["logUserId"] = $userId;
					$data["logType"] = 0;
					$data["logTime"] = date('Y-m-d H:i:s');
					db('log_orders')->insert($data);
				}
			}
		}
		return array("orderIds"=>$orderIds);
	}
	/**
	 * 获取地址详情
	 */
	private function getAddressDetails($addressId){
		$where['addressId']    = $addressId;
		$where['addressFlag']  = 1;
		$where['userId']       = $this->user['uid'];
		$address = db('User_address')->where($where)->find();
		//echo db('User_address')->getLastSql();die;
		if(empty($address))return array();
		$areaId2 = $address["areaId2"];
		$areaId3 = $address["areaId3"];
		$communityId = $address["communityId"];
		$sql = "SELECT areaId ,areaName FROM wst_areas WHERE areaId=$areaId2";
		$rs = db()->query($sql)[0];
		$cityName = $rs["areaName"];//市
	
		$sql = "SELECT areaId ,areaName FROM wst_areas WHERE areaId=$areaId3";
		$rs = db()->query($sql)[0];
		$districtsName = $rs["areaName"];//区
		$communityName = '';
		if($communityId != 0){
			$sql = "SELECT communityId ,communityName FROM wst_communitys WHERE communityId=$communityId  AND isShow =1";
			$rs = db()->query($sql);
			if($rs){
				$communityName = $rs[0]["communityName"];//社区
			}
		}
		$address["paddress"] = $cityName ." ". $districtsName ." ". $communityName;
		return $address ;
	}
	/**
	 * 订单詳情
	 */
	public function getOrderDetails(){
		$USER = $this->user['uid'];
		$morders = new Orders();
		$obj["userId"] = (int)$USER;
		//$obj["shopId"] = (int)$USER['shopId'];
		$obj["orderId"] = (int)input("orderId");
		$rs = $morders->getOrderDetails($obj);
		$data["orderInfo"] = $rs;
		// dump($data);die;
		return jsonp($data);
	}
	/**
	 * 取消订单
	 */
	public function orderCancel(){
		$USER = $this->user;
		$morders = new Orders();
		$obj["userId"] = (int)$USER['uid'];
		$obj["orderId"] = (int)input("orderId");
		$rs = $morders->orderCancel($obj);
		return jsonp($rs);
	}
	/**
	*删除订单
	*/
	public function delOrder(){
		$uid = $this->user['uid'];
		$order_id = (int)input("orderId");
		$order = db('Orders')->where("orderId=".$order_id." and orderStatus = 4")->find();
		if(!$order){
			$back = ['status'=>-1,'msg'=>'该订单无法进行此操作'];
		    return jsonp($back);
		}
		db('Orders')->where("orderId=".$order_id)->delete();
		$back = ['status'=>1,'msg'=>'操作成功'];
		return jsonp($back);
	}
	//获取不同订单状态的数量
	public function getOrderNumAllStatus(){
	    $userId = $this->user['uid'];
		
	    //待付款
	    $where[1] = " WHERE userId = $userId AND orderStatus =-2";
	    //待发货
	    $where[2] = " WHERE userId = $userId AND orderStatus in ( 0,1,2 )";
	    //待确认收货
	    $where[3] = " WHERE userId = $userId AND orderStatus =3";
	    //待评价
	    $where[4] = " WHERE userId = $userId AND orderStatus = 4";
	    //已取消
	    $where[5] = " WHERE userId = $userId AND orderStatus in (-1,-6,-7)";
	    //拒收、退款
	    $where[6] = " WHERE userId = $userId AND (orderStatus in (-3,-4,-5) or (orderStatus in (-1,-4,-6,-7) and payType =1 AND isPay =1))";
	    //待拼团
	    $where[7] = " WHERE userId = $userId AND orderStatus =-10";	
		//全部
	    $where[8] = " WHERE userId = $userId";
		$str = 'zabcdefgh';
		for($i=1;$i<=8;$i++){
	        $sql = "select count(*) as num from wst_orders ".$where[$i];
	        $num[$str[$i]] = db()->query($sql)[0]['num'];
	    }
	    return jsonp($num);
	}
	//退款
	public function runRefund(){
		$content = input('content');
		$order_id = input('order_id');
		$where['orderId'] = $order_id;
		$where['orderStatus'] = array('in',array(4,5));
		$where['userId'] = $this->user['uid'];
		$r = db('Orders')->where($where)->setField('orderStatus','-6');
		$r = db('Orders')->where($where)->setField('orderRemarks',$content);
		if($r){
			$back = ['status'=>1,'msg'=>'成功'];
	        return jsonp($back);
		}else{
			$back = ['status'=>-1,'msg'=>'失败'];
	        return jsonp($back);
		}
	}
	//触发奖励
	public function runReward($orderId,$userId){
	    $sql = "SELECT * FROM wst_orders WHERE orderFlag=1 and orderId = $orderId and userId=".$userId;
	    $rsv = db()->query($sql)[0];
	    //发奖励
	    //比例配置
	    //奖励金额 = 总 - 用代金券 - 运费
	    //$jiang = $rsv['totalMoney'] - $rsv['daijinMoney'] - $rsv['deliverMoney'] ;
	    $jiang = $rsv['totalMoney'];
	    $agent = db('Agent')->where(['area_3'=>$rsv['areaId3'],'status'=>1])->find();
	    //代理奖励
	    if($agent){
	        //增加bonus表
	        $config_agent = db('Sys_configs')->where(['fieldCode'=>'agent'])->find();
	        $bonusData = [
	            'agent_id'=>$agent['agent_id'],
	            'order_id'=>$rsv['orderId'],
	            'money'=>$jiang*$config_agent['fieldValue']/100,
	            'order_money'=>$rsv['totalMoney'],
	            'add_time'=>time(),
	            'status'=>0,
	        ];
	        $s = db('Bonus')->insert($bonusData);
	        //增加agent累计
	        db('Agent')->where(['agent_id'=>$agent['agent_id']])->setInc('daileiji',$jiang*$config_agent['fieldValue']/100);
	        //增加user贷累计
	        db('Users')->where(['userId'=>$agent['user_id']])->setInc('daili_forzen_money',$jiang*$config_agent['fieldValue']/100);
	    }
	    //用户身份
	    $userInfo = db('Users')->where(['userId'=>$userId])->find();
	    $config_jiang_one = db('Sys_configs')->where(['fieldCode'=>'jinzhituione'])->find()['fieldValue'];
	    $config_jiang_two = db('Sys_configs')->where(['fieldCode'=>'jinzhituitwo'])->find()['fieldValue'];
	    $config_jiang_one_putong = db('Sys_configs')->where(['fieldCode'=>'pu_xiao_1'])->find()['fieldValue'];
	    $pid_one = db('Users')->field('svip,tuijian_id,userId')->where(['loginName'=>$userInfo['tuijian_id']])->find();
	    $pid_two = db('Users')->field('svip,tuijian_id,userId')->where(['loginName'=>$pid_one['tuijian_id']])->find();
	    if($pid_one['svip'] == 1){
	        $add['uid'] = $userId;
	        $add['touid'] = $pid_one['userId'];
	        $add['money'] = $jiang;
	        $add['fanli'] = $jiang*$config_jiang_one/100;
	        $add['status'] = 0;
	        $add['orderId'] = $rsv['orderId'];
	        $add['time'] = time();
	        db('Tuishou_jilu')->insert($add);
	    }else{
			$add['uid'] = $userId;
	        $add['touid'] = $pid_one['userId'];
	        $add['money'] = $jiang;
	        $add['fanli'] = $jiang*$config_jiang_one_putong/100;
	        $add['status'] = 0;
	        $add['orderId'] = $rsv['orderId'];
	        $add['time'] = time();
	        db('Tuishou_jilu')->insert($add);
		}
	    if($pid_two['svip'] == 1){
	        $add1['uid'] = $userId;
	        $add1['touid'] = $pid_two['userId'];
	        $add1['money'] = $jiang;
	        $add1['fanli'] = $jiang*$config_jiang_two/100;
	        $add1['status'] = 0;
	        $add1['orderId'] = $rsv['orderId'];
	        $add1['time'] = time();
	        db('Tuishou_jilu')->insert($add1);
	    }
	}
}